package org.thesis.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.mail.Message;

import org.thesis.dataAccess.DB_EmailLoginManager_Adapter;
import org.thesis.dataAccess.db_email;
import org.thesis.doituong.OneMail;
import org.thesis.doituong.attach;
import org.thesis.doituong.showToast;
import org.thesis.mailControl.GmailControl;
import org.thesis.mailControl.HotmailControl;
import org.thesis.mailControl.MdeamonControl;
import org.thesis.mailControl.YahooControl;
import org.thesis.secutity.AESControl;
import org.thesis.secutity.DEScontrol;
import org.thesis.secutity.KeyManager;
import org.thesis.secutity.RSAControl;
import org.thesis.secutity.TripleDEScontrol;
import org.thesis.secutity.webserviceRequest;
import org.thesis.xuly.ConvertMessageToList;
import org.thesis.xuly.XuLyChuoi;
import org.thesis.xuly.XulySql;


import uit.mmt02.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.TextView;

public class readmailActivity extends Activity
{
	showToast st ;
//	final static String KEY_SUB = "SUB";
//	final static String KEY_FROM = "FROM";
//	final static String KEY_TO = "TO";
//	final static String KEY_TIME = "TIME";
//	final static String KEY_BODY = "BODY";
//	final static String KEY_FAVORITE = "FAVORITE";
//	final static String KEY_BUNDLE = "BUNDLE";
	final static String ENC_PUBLIC = "ENC4";
	final static String ENC_AES = "AES";
	final static String ENC_DES = "DES";
	final static String ENC_TDES = "3DES";
	final static String ENC_FOOT = "@encrypt";
	final static String PUBLIC_KEY = "ENC4";
	final static String PATH_GET_KEY_DE = "/EncryptEmail/getkey_de/";
	final static String PATH_PUBLIC = "/EncryptEmail/keymail/";
	final static String KEY_ARRAY_TO_NEWMAIL = "KeyArrToNewMail";
	final static String LOAI_SEND = "LOAISEND";
	final static String NEWMAIL = "NEWMAIL";
	final static String REPLY = "REPLY";
	final static String FORWARD = "FORWARD";
	final static String KEY_USERNAME_LOGIN = "USERNAMELOGIN"; // nhan USERVA PASS tu showmail activity gui toi de login
	final static String KEY_PASSWORD_LOGIN = "PASSWORDLOGIN";
	
	final static String KEY_STT = "_stt";
	final static String KEY_DB = "_key_db";
	final static String KEY_MESS = "message";
	final static String KEY_USERNAME = "username";
	final static String KEY_PASSWORD = "password";
	final static String KEY_LOAIEMAIL = "loai_email";
	final static String KEY_STR_ATTACH = "chuoi_attach";
	final static String KEY_NGUOIGUI = "NGUOIGUI";
	final static String KEY_NGUOIGUI_NGUOINHAN = "KEY_NGUOIGUI_NGUOINHAN";
	
	TextView txt_int_att, txtstt,txtsub, txtfrom, txtto, txttime, txtbody,
			txtbody_dec, //tv chuoi sau giai ma
			txt_sign;  //tv xac nhan chung thuc
    CheckBox cb_favorite;
    ImageButton btn_att_view;
    ImageButton img_int_att, img_next, img_back, img_attach, img_encrypt, img_voice, img_decrypt;
//    ListView lv_attach;
//    ArrayAdapter<String>adapter;
    //
    int stt;
    db_email mydb;
    XulySql xulysql;
    XuLyChuoi xulychuoi;
    String db_name;
    String tag = "readmailActivity";
    List<String>list_str_attach;
    
    //
    List<attach>list;
//    ArrayAdapter<attach>adapter;
    
    //
    OneMail omG;
    //
    String username;
    String password;
    Message []mess;
    ConvertMessageToList cv;
    XuLyChuoi xlchuoi ;
	String loai_email;
    GmailControl g;
    YahooControl y;
    HotmailControl h;
    MdeamonControl md;
    DB_EmailLoginManager_Adapter db_login;
    String str_att;
    
    ///
    String str_sha,str_de_sign, str_sign,str_mess_encrypt, str_loaimahoa, 
    	str_nguoigui_nguoinhan, str_namekeyfile, str_pathkey, str_mess_decrypt;///
    String str_nguoigui;////
    String[] str_mess_send;///
    org.thesis.secutity.AESControl AEScontrol;///
    org.thesis.secutity.webserviceRequest webservice;///
    org.thesis.secutity.KeyManager keymanager;///
    
    AESControl aes;
    DEScontrol des;
    TripleDEScontrol tdes;
    RSAControl rsa;
    String str_ngnhan2;
    String []value;
    Intent intent;
    String s_sub, s_from;
    boolean flag_sign,flag_enc,flag_getkey,flag_getkey_sign = false,flag_signOK = false,
    		flag_decrypt_pri, flag_attach;
    String progress,progress2;
    String thongbao;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
	    
	    
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.read_mail); 
		st = new showToast(getBaseContext());
		stt = getIntent().getIntExtra(KEY_STT, 0);
		db_name = getIntent().getStringExtra(KEY_DB);
		username = getIntent().getStringExtra(KEY_USERNAME);
		Log.v(tag, "username : " + username);
		db_login = new DB_EmailLoginManager_Adapter(this);
		password = db_login.db_getpassword(username);
		txtstt = (TextView)findViewById(R.id.txt_readmail_stt);
		txtsub = (TextView)findViewById(R.id.txt_readmail_sub);
		txtfrom = (TextView)findViewById(R.id.txt_readmail_from);
		txtto = (TextView)findViewById(R.id.txt_readmail_to);
		txttime = (TextView)findViewById(R.id.txt_readmail_time);
		txtbody = (TextView)findViewById(R.id.txt_readmail_body);
		txt_int_att = (TextView)findViewById(R.id.txt_readmail_int_att);
		txtbody_dec = (TextView) findViewById(R.id.txt_readmail_bodyDecrypt);
		txt_sign = (TextView) findViewById(R.id.txt_readmail_body_sign);
		//
		
		//
		img_next = (ImageButton)findViewById(R.id.img_readmail_next);
		img_back = (ImageButton)findViewById(R.id.img_readmail_back);
		img_attach = (ImageButton)findViewById(R.id.img_readmail_att);
		img_encrypt = (ImageButton)findViewById(R.id.img_readmail_encrypt);
		img_voice = (ImageButton)findViewById(R.id.img_readmail_voice);
		img_decrypt = (ImageButton)findViewById(R.id.img_readmail_decrypt);
		img_int_att = (ImageButton)findViewById(R.id.img_readmail_int_attach);
		cb_favorite = (CheckBox)findViewById(R.id.cb_readmail_favorite);
		mydb = new db_email(this, db_name);
		xulysql = new XulySql();
		xulychuoi = new XuLyChuoi();
		
		
		//
		g = new GmailControl(username, password);
		y = new YahooControl(username, password);
		h = new HotmailControl(username, password);
		md = new MdeamonControl(username, password);
		cv = new ConvertMessageToList();
		xlchuoi = new XuLyChuoi();
		loai_email = xlchuoi.kt_loai_email_login(username);
		keymanager = new KeyManager();
		str_loaimahoa = "";
		if(stt != 0)
		{
			read_mail2(stt);
		}
		show_int_att();
		//
		
	};
	
	public void btn_onClick(View v)
	{
		Button  btn = (Button)v;
		switch (btn.getId()) {
		default:
			break;
		}
	}
	

	public void img_onClick(View v)
	{
		ImageButton img = (ImageButton)v;
		switch (img.getId()) {
		case R.id.img_readmail_backA:
			finish();
			break;
		case R.id.img_readmail_menu:
			openOptionsMenu();
			break;
		case R.id.img_readmail_int_attach:
			Intent i_att = new Intent(this, attach_download_Activity.class);
			i_att.putExtra(KEY_USERNAME, username);
			i_att.putExtra(KEY_PASSWORD, password);
			i_att.putExtra(KEY_LOAIEMAIL, loai_email);
			i_att.putExtra(KEY_STR_ATTACH, str_att);
			i_att.putExtra(KEY_STT, stt);
			i_att.putExtra(KEY_NGUOIGUI,str_nguoigui);
			i_att.putExtra(KEY_NGUOIGUI_NGUOINHAN, str_nguoigui_nguoinhan);
			startActivity(i_att);
			break;
		case R.id.img_readmail_att:
			break;
		case R.id.img_readmail_decrypt:
//			decrypt();
//			sign_check();
			if(flag_enc)
				decrypt_action();
			else
			{
				str_mess_decrypt = str_mess_encrypt; // neu k ma ma hoa, gan chuoi ma hoa la chuoi plantext de hash
				if(flag_sign)
					sign_action();
			}
			
			break;
		case R.id.img_readmail_next:
			stt ++;
			img_back.setEnabled(true);
			if(stt <= 10)
			{
				read_mail2(stt);
			}
			else
			{
				img_next.setEnabled(false);
			}
			show_int_att();
			break;
		case R.id.img_readmail_back:
			img_next.setEnabled(true);
			stt --;
			if(stt > 0 )
			{
				read_mail2(stt);
			}
			else
			{
				img_back.setEnabled(false);
			}
			show_int_att();
			break;

		default:
			break;
		}
	}
	
	public void read_mail2(int _stt)
	{
		try 
		{
			
			txt_sign.setText("");
			Log.v(tag, "readmail 2");
			flag_sign = false;
			flag_enc = false;
			flag_getkey = false;
			flag_attach = false;
			mydb.open();
			Cursor mCursor = mydb.query_get_by_stt(stt);
			OneMail mail = xulysql.cv_get_by_stt(mCursor);
			mCursor.close();
			mydb.close();
			txtstt.setText("---- "+String.valueOf(mail.getId())+ "----");
			s_sub = mail.getSub();
			s_from = mail.getFrom();
			txtsub.setText(getResources().getString(R.string.mail_sub) + s_sub);
			txtfrom.setText(getResources().getString(R.string.mail_from) + s_from);
			txtto.setText(getResources().getString(R.string.mail_to)+mail.getTo2());
			txttime.setText(mail.getDateSend());
			String str_body = mail.getBody();
			txtbody.setText(str_body);
			
			//
			txtbody_dec.setText("");
			//
			
			if(mail.isFlagVoice())
				img_voice.setVisibility(ImageButton.VISIBLE);
			else
				img_voice.setVisibility(ImageButton.GONE);
			
			if(mail.isFlagFavorite())
				cb_favorite.setChecked(true);
			else
				cb_favorite.setChecked(false);
			//xu ly attach
			list_str_attach = new ArrayList<String>();
			str_att = "";
			if(mail.isFlagAttach())
			{
				flag_attach = true;
				img_attach.setVisibility(ImageButton.VISIBLE);
//				img_save.setVisibility(ImageButton.VISIBLE);
				//thuc hien add list add vao
				str_att = mail.getStr_attach2();
				Log.v(tag + "-readmail 2", "chuoi attach " + str_att);
				list_str_attach = xulychuoi.getList_str_attach(str_att);
			}
			
			else
			{
				img_attach.setVisibility(ImageButton.GONE);
			}
			//xy ly message body, kiem tra co ma hoa ko
			
			if(xlchuoi.check_encrypt(str_body) || xlchuoi.check_sign(str_body))
			{
				////lay dia chi nguoi gui de check ten public key trong sdcard va goi web service;
				str_nguoigui  = mail.getFrom().toString().trim().replaceAll(".*?<", "").replaceAll(">.*?", "");
				Log.v(tag, "str_nguoigui="+str_nguoigui);
				
				////lay ten nguoigui_nguoinhan de xu ly kiem tra key trong sdcard va goi webService;
				// str_nguoigui_nguoinhan = "addressfrom;addressto"--> addressfrom addressto;
				String[] arr_nguoinhan = mail.getTo2().split(";");
				for (int i = 0; i < arr_nguoinhan.length; i++) {
					if (i == 0) {
						str_ngnhan2 = arr_nguoinhan[i].trim()
								.replaceAll(".*?<", "").replaceAll(">.*?", "")
								+ ";";
					} else {
						str_ngnhan2 = str_ngnhan2
								+ arr_nguoinhan[i].trim()
										.replaceAll(".*?<", "")
										.replaceAll(">.*?", "") + ";";
					}
				}
				str_nguoigui_nguoinhan  = str_nguoigui+";"+str_ngnhan2;///
				str_nguoigui_nguoinhan  = str_nguoigui_nguoinhan.replaceAll(";", " ");
				////
				
				img_encrypt.setVisibility(ImageButton.VISIBLE);
				img_decrypt.setVisibility(ImageButton.VISIBLE);
				
				if(xlchuoi.check_encrypt(str_body)) // co ma hoa
				{
					flag_enc = true;
					str_loaimahoa = str_body.split("@")[0].trim();
					Log.v(tag, "loai ma hoa:" + str_loaimahoa);
					str_mess_encrypt = xlchuoi.get_str_encrypt(str_body, str_loaimahoa);
					Log.v(tag, "chuoi ma hoa : " +str_mess_encrypt);
				}
				if(xlchuoi.check_sign(str_body))
				{
					//luc nay chuoi str_mess_encrypt la
					if(!flag_enc)
						str_mess_encrypt = xlchuoi.get_platext_have_sign(str_body);
					str_sign = xlchuoi.get_str_sign(str_body);
					Log.v(tag, "chuoi ky : " + str_sign);
					flag_sign = true;
				}
			}
			else
			{
				img_encrypt.setVisibility(ImageButton.GONE);
				img_decrypt.setVisibility(ImageButton.GONE);
				
				//lay str_nguoi_ngnhan de gui qua ben dow att
				str_nguoigui  = mail.getFrom().toString().trim().replaceAll(".*?<", "").replaceAll(">.*?", "");
				Log.v(tag, "str_nguoigui="+str_nguoigui);
				
				////lay ten nguoigui_nguoinhan de xu ly kiem tra key trong sdcard va goi webService;
				// str_nguoigui_nguoinhan = "addressfrom;addressto"--> addressfrom addressto;
				String[] arr_nguoinhan = mail.getTo2().split(";");
				for (int i = 0; i < arr_nguoinhan.length; i++) {
					if (i == 0) {
						str_ngnhan2 = arr_nguoinhan[i].trim()
								.replaceAll(".*?<", "").replaceAll(">.*?", "")
								+ ";";
					} else {
						str_ngnhan2 = str_ngnhan2
								+ arr_nguoinhan[i].trim()
										.replaceAll(".*?<", "")
										.replaceAll(">.*?", "") + ";";
					}
				}
				str_nguoigui_nguoinhan  = str_nguoigui+";"+str_ngnhan2;///
				str_nguoigui_nguoinhan  = str_nguoigui_nguoinhan.replaceAll(";", " ");
				
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag, "loi read mail 2" + e.toString());
			mydb.close();
		}
		
	}
	public void remove_list()
	{
		try
		{
			
			for(int i = list.size() -1 ; i >= 0; i--)
			{
				list.remove(i);
				Log.v(tag, "remove " + i);
			}
//			adapter.notifyDataSetChanged();
		}catch (Exception e) {
			// TODO: handle exception
			Log.v(tag, "ko the remove all");
		}
	}
	
	public void save_att()
	{
		get_loai_mail();
		
		try
		{
			int i_down =  mess.length - stt;
//			Log.v(tag, mess[i_down].getSubject().toString());
			for(int i = 0 ; i < list.size(); i++)
			{
				if(list.get(i).isCheck())
				{
					//save con i
					Log.v(tag, "vao save _att");
					cv.Download_by_name(mess, i_down , i);
				}
			}
			
		}catch (Exception e) {
			// TODO: handle exception
			Log.v(tag, "Err save att " +e.toString());
		}
		
	}
	public void open_forder_download()
	{
		try
		{
			AlertDialog.Builder buider = new AlertDialog.Builder(this);
			buider.setMessage("Open forder Download ...");
			buider.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					
				}
			});
			buider.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					return;
				}
			});
			
			AlertDialog alert = buider.create();
			alert.show();
			
		}catch (Exception e) {
			// TODO: handle exception
			Log.e(tag, "err open_download " +e.toString());
		}
	}
	
	public void get_loai_mail()
	{
		if(loai_email.startsWith("gmail"))
			mess = g.getmail();
		else if(loai_email.startsWith("yahoo"))
		{
			mess = y.getmail();
		}	//
		else if(loai_email.startsWith("hotmail"))
		{
			//
			mess = h.getmail();
		}
	}
	
	
	public void show_int_att()
	{
		txt_int_att.setText(String.valueOf(list_str_attach.size()));
		if(list_str_attach.size() == 0)
			img_int_att.setEnabled(false);
		else
			img_int_att.setEnabled(true);
	}
	
	//tao menu
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater m_MenuInflater = getMenuInflater();
		m_MenuInflater.inflate(R.menu.menu_read_mail, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.item_readmail_newmail:
			value = new String[10];
			value[0] = username;
			value[1] = password;
			value[2] = NEWMAIL;
			intent = new Intent(this, org.thesis.activity.newmailActivity.class);
			intent.putExtra(KEY_ARRAY_TO_NEWMAIL, value);
			startActivity(intent);
			break;
		case R.id.item_newmail_reply:
			value = new String[10];
			value[0] = username;
			value[1] = password;
			value[2] = REPLY;
			value[3] = getResources().getString(R.string.mail_reply)+ " : " + s_sub;
			value[4] = s_from; // ng nhan
			
			intent = new Intent(this, org.thesis.activity.newmailActivity.class);
			intent.putExtra(KEY_ARRAY_TO_NEWMAIL, value);
			startActivity(intent);
			
			break;
		case R.id.item_newmail_forward:
			value = new String[10];
			value[0] = username;
			value[1] = password;
			value[2] = FORWARD;
			value[3] = getResources().getString(R.string.mail_forward)+ " : " + s_sub;
			value[4] = "\n\r\n\r" + "*****************" + "\n\r " + txtbody.getText().toString();
			intent = new Intent(this, org.thesis.activity.newmailActivity.class);
			intent.putExtra(KEY_ARRAY_TO_NEWMAIL, value);
			startActivity(intent);
			break;
		case R.id.item_readmail_decrypt:
			if(flag_enc || flag_sign)
			{
				if(flag_enc)
					decrypt_action();
				else
				{
					str_mess_decrypt = str_mess_encrypt; // neu k ma ma hoa, gan chuoi ma hoa la chuoi plantext de hash
					if(flag_sign)
						sign_action();
				}
			}
			else
				st.showmess(getResources().getString(R.string.no_enc_sign));
			break;
		case R.id.item_readmail_attach:
			if(flag_attach)
				///
			{
				Intent i_att = new Intent(this, attach_download_Activity.class);
				i_att.putExtra(KEY_USERNAME, username);
				i_att.putExtra(KEY_PASSWORD, password);
				i_att.putExtra(KEY_LOAIEMAIL, loai_email);
				i_att.putExtra(KEY_STR_ATTACH, str_att);
				i_att.putExtra(KEY_STT, stt);
				i_att.putExtra(KEY_NGUOIGUI,str_nguoigui);
				i_att.putExtra(KEY_NGUOIGUI_NGUOINHAN, str_nguoigui_nguoinhan);
				startActivity(i_att);
				break;
			}
				
			else
				st.showmess(getResources().getString(R.string.no_att));

		default:
			break;
		}
		
		return super.onOptionsItemSelected(item);
	}
	
	
	///
	public void readmail_decrypt(){
		try{
			
			str_namekeyfile = str_nguoigui_nguoinhan+str_loaimahoa+".key";
			Log.v(tag, "file key name  " + str_namekeyfile);
			String path_de = Environment.getExternalStorageDirectory().getAbsolutePath() + PATH_GET_KEY_DE;
			Log.v(tag, "path save : " + path_de);
			File savedirsub = new File(path_de);
			if(!savedirsub.isDirectory())
			{
				Log.v(tag, "tao thu muc " + path_de);
				savedirsub.mkdirs();
			}
			else
				Log.v(tag, "da ton tai thu muc , ko tao");
//			str_pathkey = Environment.getExternalStorageDirectory().getAbsolutePath()+PATH_PUBLIC+str_namekeyfile;
			str_pathkey = path_de +str_namekeyfile;
			Log.v(tag, "file key save : " + str_pathkey);
			File f = new File(str_pathkey);
	        if(!f.isFile())
	        {
	        	//chua co key trong thu muc emailkey ==>thong bao click tao key
				Log.i(tag, "chua co key trong thu muc emailkey ==>xin key ");
//				Toast.makeText(getBaseContext(), "Chua co key, dang xin key", Toast.LENGTH_SHORT).show();
				webservice = new org.thesis.secutity.webserviceRequest(str_nguoigui_nguoinhan, str_loaimahoa);
				webservice.getkeyStringDecrypt();
				Log.v(tag,"Xin key success...");
	        	
	        }
	        else
	        {
	        	Log.i(tag,"co key trong thu muc emailkey ==> goi ham giai ma");
	        }
				//co key trong thu muc emailkey ==> goi ham giai ma==> doc file key, lay key ma hoa;
	        	keymanager = new org.thesis.secutity.KeyManager();
	        	if(str_loaimahoa.equalsIgnoreCase("AES"))
	        	{
						AEScontrol = new org.thesis.secutity.AESControl(keymanager.getKeyAES(str_pathkey));
						str_mess_decrypt = AEScontrol.Decrypt(str_mess_encrypt);
						Log.v("DECRYPT MESS = ", str_mess_decrypt);
						txtbody.setText(str_mess_decrypt);
						//Toast.makeText(getBaseContext(), "giai ma:"+str_mess_send, Toast.LENGTH_SHORT).show();
						// mahoa_file();
						// giama_file();
				}							
	        					
			
		}catch(Exception e){
			Log.v(tag, "ERROR: "+e.toString());
		}
	}
	
	//ko xu dung, su hdung ham check trog xulychuoi
	public boolean check_body_encrypt(String str)
	{
		boolean check = false;
		try {
			String []arr_body = str.split("@");
			String s = arr_body[0];
			if(s.equals("AES") || s.equals("DES") || s.equals("3DES"))
				return true;
			
		} catch (Exception e) {
			// TODO: handle exception
			Log.v(str, "loi check body encry pt" + e.toString());
		}
		return check;
	}
	
	public void decrypt() //giai ma thu co ma hoa
	{
		try {
			//1.xac dinh loai ma hoa la gi
			//2.Tim key co trong may ko (neu ko tien hanh xin key tu server)
			//3. su dung key giai ma
			//
			
			String path_de = Environment.getExternalStorageDirectory().getAbsolutePath() + PATH_GET_KEY_DE;
			Log.v(tag, "thu muc chua key giai ma : " + path_de);
			File savedirsub = new File(path_de);
			if(!savedirsub.isDirectory())
			{
				Log.v(tag, "tao thu muc " + path_de);
				savedirsub.mkdirs();
			}
			else
				Log.v(tag, "da ton tai thu muc chua key, ko tao");
			str_namekeyfile = "";
			if(str_loaimahoa.equals("AES"))
			{
				//tim key
				str_namekeyfile = "keyaes.key"; //sau chinh dua o day
				str_pathkey = path_de +str_namekeyfile;
				Log.v(tag, "file key save : " + str_pathkey);
				File f = new File(str_pathkey);
		        if(!f.isFile())
		        {
		        	Log.v(tag, "chua ton tai key aes, tien hanh xin key....");
		        	//async xin key
		        }else
		        {
		        	Log.v(tag, "da co key aes, tien hanh giai ma truc tiep");
		        	aes = new AESControl(keymanager.getKeyAES(str_pathkey));
		        	str_mess_decrypt = aes.Decrypt(str_mess_encrypt);
		        }
				
			}
			if(str_loaimahoa.equals("DES"))
			{
				str_namekeyfile = "keydes.key";
				str_pathkey = path_de +str_namekeyfile;
				Log.v(tag, "file key save : " + str_pathkey);
				File f = new File(str_pathkey);
		        if(!f.isFile())
		        {
		        	Log.v(tag, "chua ton tai key DES, tien hanh xin key....");
		        }else
		        {
		        	Log.v(tag, "da co key DES, tien hanh giai ma truc tiep");
		        	des = new DEScontrol(keymanager.getKeyDES(str_pathkey));
		        	str_mess_decrypt = des.Decrypt(str_mess_encrypt);
		        }
			}
			if(str_loaimahoa.equals("3DES"))
			{
				str_namekeyfile = "key3des.key";
				str_pathkey = path_de +str_namekeyfile;
				Log.v(tag, "file key save : " + str_pathkey);
				File f = new File(str_pathkey);
		        if(!f.isFile())
		        {
		        	Log.v(tag, "chua ton tai key 3DES, tien hanh xin key....");
		        }else
		        {
		        	Log.v(tag, "da co key 3DES, tien hanh giai ma truc tiep");
		        	tdes = new TripleDEScontrol(keymanager.getKey3DES(str_pathkey));
		        	str_mess_decrypt = tdes.decrypt(str_mess_encrypt);
		        }
			}
			txtbody_dec.setText(str_mess_decrypt);
			
				
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag, "loi decrypt " +e.toString());
		}
	}
	
	public void sign_check() //kiem tra chung thuc thu ky
	{
		try 
		{
			String path_de = Environment.getExternalStorageDirectory().getAbsolutePath() + PATH_GET_KEY_DE;
			Log.v(tag, "thu muc chua key giai ma : " + path_de);
			File savedirsub = new File(path_de);
			if(!savedirsub.isDirectory())
			{
				Log.v(tag, "tao thu muc " + path_de);
				savedirsub.mkdirs();
			}
			else
				Log.v(tag, "da ton tai thu muc chua key, ko tao");
			str_namekeyfile = "";
			String thongbao  = getResources().getString(R.string.nosign);
			if(flag_sign)
			{
				Log.v(tag, "kiem tra sign");
				//str_namekeyfile = "keypu.key";
				str_namekeyfile  = str_nguoigui+" keypu.key";////
				str_pathkey = path_de +str_namekeyfile;
				Log.v(tag, "File key pu: " + str_pathkey);
				File f = new File(str_pathkey);
				
		        if(!f.isFile())
		        {
		        	Log.v(tag, "chua ton tai key public, tien hanh xin key....");////
		            webservice  = new  webserviceRequest(str_nguoigui_nguoinhan, "RSApu");
		            webservice.requestPuRSAKey_sign();
		            Log.v(tag, "lay public key  thanh cong");
		        }else
		        {
		        	Log.v(tag, "da co key public, tien hanh giai ma truc tiep");
		        	rsa = new RSAControl(str_pathkey, false);
					// su dung public key giai ma chuoi sign
					
					str_de_sign = rsa.de_sign(str_sign);
					
					//ban noi dung m ra roi ss sanh voi str_de_sign
					str_sha = rsa.hash_sha(str_mess_decrypt);
//					thongbao = "Giai ma chuoi ky : " + Base64.decode(str_de_sign, 1) 
//							+ "\n\r" + "Hash Noi dung goc : " + Base64.decode(str_sha, 1);
					thongbao = getResources().getString(R.string.sign_de)+ " : " + Base64.decode(str_de_sign, 1) 
							+ "\n\r" + getResources().getString(R.string.hash) + " : " + Base64.decode(str_sha, 1);
					
					
					if(str_de_sign.equals(str_sha))
					{
//						thongbao += "\n\r ==> Chung thuc thanh cong";
						thongbao += "\n\r ==> " + getResources().getString(R.string.sign_success);
						txt_sign.setBackgroundColor(getResources().getColor(R.color.green));
					}
					else
					{
//						thongbao += " \n\r ==> Chung thuc khong thanh cong";
						thongbao += "\n\r ==> " + getResources().getString(R.string.sign_Unsuccess);
						txt_sign.setBackgroundColor(getResources().getColor(R.color.red));
					}
		        	
		        }
			}
			txt_sign.setText(thongbao);
			
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag, "Loi check sign " +e.toString());
		}
	}
	
	private class sync_decrypt extends AsyncTask<String, String, String>
	{
		
		ProgressDialog p = new ProgressDialog(readmailActivity.this);
		
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			p.setMessage(progress);
			p.show();
		}
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			if(flag_getkey)
			{
				getkey_decrypt();
			}
			else
			{
				giaima();
			}
			return null;
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			p.dismiss();
			st.showmess(progress2);
			txtbody_dec.setText(str_mess_decrypt);
			boolean flag_temp = true; // co cho phep ham check sing hoat dong
			if(flag_getkey) // sau khi xin key thuc hien giai ma truc tiep, tranh truong hop dang xin key cho ma hoa de tien hanh check sign
			{
				flag_temp = false;
				progress = "xin key thanh cong, tien hanh giai ma";
				decrypt_action();
			}
			// sau khi ma hoa xong tien hanh kiem tra chu ky
			if(flag_temp)
			{
				if(flag_sign)
					sign_action();
			}
			super.onPostExecute(result);
		}
	
	}
	
	public void getkey_decrypt() //get key de ma hoa
	{
		try 
		{
			if(flag_decrypt_pri) // xin key bat doi xung
			{
				Log.v(tag, "file key chua ton tai , bat dau xin key private rsa");////
				webservice   = new  webserviceRequest(str_nguoigui_nguoinhan, "RSApi");
				webservice.requestMyRSAKey();
				Log.v(tag, "xin key thanh cong");
			}
			else  // xin key doi xung
			{
				Log.i(tag + " getkey_decrypt", "xin key ");
				webservice = new org.thesis.secutity.webserviceRequest(str_nguoigui_nguoinhan, str_loaimahoa);
				webservice.getkeyStringDecrypt();
				Log.i(tag + " getkey dec","Xin key success...");
			}
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag + "::getkey_de", e.toString());
		}
	}
	
	public void decrypt_action()
	{
		try 
		{
			//1.xac dinh loai ma hoa la gi
			//2.Tim key co trong may ko (neu ko tien hanh xin key tu server)
			//3. su dung key giai ma
			//
			String path_de ;
			File savedirsub;
			flag_decrypt_pri = false;
			path_de = Environment.getExternalStorageDirectory().getAbsolutePath() + PATH_GET_KEY_DE;
			savedirsub = new File(path_de);
			if(!savedirsub.isDirectory())
			{
				Log.v(tag, "tao thu muc " + path_de);
				savedirsub.mkdirs();
			}
			else
				Log.v(tag, "da ton tai thu muc chua key, ko tao");
			
			str_namekeyfile = str_nguoigui_nguoinhan+" "+str_loaimahoa;////
		 		Log.v("str_namekeyfile = ",  str_namekeyfile);////
		 	
		 		str_pathkey = path_de +str_namekeyfile;
		 		if(str_loaimahoa.equalsIgnoreCase(PUBLIC_KEY)) // neu ng gui dung public key gui, su dung file key khac
		 		{
		 			flag_decrypt_pri = true;
		 			savedirsub = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+PATH_PUBLIC);
			 		if(!savedirsub.isDirectory())
			 		{
							savedirsub.mkdirs();
							Log.v(tag,"tao thu muc");
			 		}
 				String path_key_pri = Environment.getExternalStorageDirectory().getAbsolutePath()+PATH_PUBLIC+str_nguoigui+" keypri.key";////
 				Log.v(tag, "path_key_pri = "+path_key_pri);////
 				str_pathkey = path_key_pri;
		 			
		 		}
				Log.v(tag, "file key save : " + str_pathkey);
				File f = new File(str_pathkey);
		        if(!f.isFile())
		        {
		        	progress = getResources().getString(R.string.dec_notkey_getkey);
		        	progress2 =getResources().getString(R.string.getkey_suc);
		        	flag_getkey = true;
		        	Log.v(tag+"::encrypt_action", "chua co key, xin key");
		        	
		        }
		        else
		        {
		        	Log.v(tag+"::encrypt_action", "thuc hien giai ma");
		        	progress = getResources().getString(R.string.dec_doinng);
		        	progress2 = getResources().getString(R.string.dec_suc);
		        	flag_getkey = false;
		        }
		        new sync_decrypt().execute("decrypt");
			
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag+"::decrypt_action", e.toString());
		}
	}
	
	public void giaima()
	{
		try {
			if(str_loaimahoa.equalsIgnoreCase(ENC_AES))
			{
				Log.v(tag, "da co key aes, tien hanh giai ma truc tiep");
	        	aes = new AESControl(keymanager.getKeyAES(str_pathkey));
	        	str_mess_decrypt = aes.Decrypt(str_mess_encrypt);
			}else if(str_loaimahoa.equalsIgnoreCase(ENC_DES))
			{
				Log.v(tag, "da co key DES, tien hanh giai ma truc tiep");
	        	des = new DEScontrol(keymanager.getKeyDES(str_pathkey));
	        	str_mess_decrypt = des.Decrypt(str_mess_encrypt);
			}else if( str_loaimahoa.equalsIgnoreCase(ENC_TDES))
			{
				Log.v(tag, "da co key 3DES, tien hanh giai ma truc tiep");
	        	tdes = new TripleDEScontrol(keymanager.getKey3DES(str_pathkey));
	        	str_mess_decrypt = tdes.decrypt(str_mess_encrypt);
			}else if (str_loaimahoa.equalsIgnoreCase(PUBLIC_KEY))
			{
				Log.v(tag, "da co key private, tien hanh giai ma truc tiep");
				rsa = new RSAControl(str_pathkey, true);
				str_mess_decrypt = rsa.decrypt_baomat(str_mess_encrypt);
			}
			Log.v(tag+" giaima", str_mess_decrypt);
			
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag+"::giaima", e.toString());
		}
	}
	
	public void sign_action()
	{
		try 
		{	
			String path_de = Environment.getExternalStorageDirectory().getAbsolutePath() + PATH_GET_KEY_DE;
			File savedirsub = new File(path_de);
			if(!savedirsub.isDirectory())
			{
				Log.v(tag, "tao thu muc " + path_de);
				savedirsub.mkdirs();
			}
			else
				Log.v(tag, "da ton tai thu muc chua key, ko tao");
			str_namekeyfile = "";
			thongbao  = getResources().getString(R.string.nosign);
			//str_namekeyfile = "keypu.key";
			str_namekeyfile  = str_nguoigui+" keypu.key";////
			str_pathkey = path_de +str_namekeyfile;
			Log.v(tag, "File key pu: " + str_pathkey);
			File f = new File(str_pathkey);
			if(!f.isFile())
	        {
	        	Log.v(tag, "chua ton tai key public, tien hanh xin key....");////
	        	progress = "xin key public de tien hanh kiem tra chu ky";
	        	progress2 =getResources().getString(R.string.getkey_suc);
	        	flag_getkey_sign = true;
	            
	        }else
	        {
	        	progress = getResources().getString(R.string.sign_check);
	        	progress2 = getResources().getString(R.string.sign_suc);
	        	flag_getkey_sign = false;
	        }
			new sync_sign().execute("sign");
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag+" sign action", e.toString());
		}
	
	}
	
	public void getkey_public() // xin key public tren sv de tien hanh kiem tra chu ky
	{
		try {
			webservice  = new  webserviceRequest(str_nguoigui_nguoinhan, "RSApu");
            webservice.requestPuRSAKey_sign();
            Log.v(tag, "lay public key  thanh cong");
			
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag+" get key public", e.toString());
		}
	}
	
	private class sync_sign extends AsyncTask<String, String, String>
	{
		
		ProgressDialog p = new ProgressDialog(readmailActivity.this);
		
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			p.setMessage(progress);
			p.show();
		}
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			if(flag_getkey_sign)
			{
				getkey_public();
			}
			else
			{
				kiem_tra_chuky();
			}
			return null;
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			p.dismiss();
			st.showmess(progress2);
//			txtbody_dec.setText(str_mess_decrypt);
			txt_sign.setText(thongbao);
			if(flag_getkey_sign) // sau khi xin key thuc hien giai ma truc tiep
			{
				progress = "xin key thanh cong, tien hanh kiem tra chu ky";
//				new sync_decrypt().execute("decrypt2");
				sign_action();
			}
			if(flag_signOK)
				txt_sign.setBackgroundColor(getResources().getColor(R.color.green));
			else
				txt_sign.setBackgroundColor(getResources().getColor(R.color.red));
			super.onPostExecute(result);
		}
	
	}
	
	public void kiem_tra_chuky()
	{
		try {
			Log.v(tag, "da co key public, tien hanh giai ma truc tiep");
        	rsa = new RSAControl(str_pathkey, false);
			// su dung public key giai ma chuoi sign
			
			str_de_sign = rsa.de_sign(str_sign);
			
			//ban noi dung m ra roi ss sanh voi str_de_sign
			str_sha = rsa.hash_sha(str_mess_decrypt);
			thongbao = getResources().getString(R.string.sign_de)+ " : " + Base64.decode(str_de_sign, 1) 
					+ "\n\r" + getResources().getString(R.string.hash) + " : " + Base64.decode(str_sha, 1);
			
			
			if(str_de_sign.equals(str_sha))
			{
				thongbao += "\n\r ==> " + getResources().getString(R.string.sign_success);
//				txt_sign.setBackgroundColor(getResources().getColor(R.color.green));
				flag_signOK = true;
			}
			else
			{
				thongbao += "\n\r ==> " + getResources().getString(R.string.sign_Unsuccess);
//				txt_sign.setBackgroundColor(getResources().getColor(R.color.red));
				flag_signOK = false;
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag + " kiemtra chuky", e.toString());
		}
	}
	
	
}
